#include <stdio.h>
#include "gpio_init.h"
#include <stdlib.h>

int main(int argc, char **argv)
{
    if (argc < 2)
    {
        fprintf(stderr, "./led <val>");
        printf("  <val>: 1(open), 2(close)");
        exit(-1);
    }
    struct gpio_desc gpios;
    char gpio_num[6];
    char pptr[128];
    int fd, len;

    gpio_init(); // 初始化引脚

    gpios.group = 0;
    gpios.num[0] = 13;
    memset(gpio_num, 0, sizeof(gpio_num) / sizeof(char));
    memset(pptr, 0, sizeof(pptr) / sizeof(char));
    sprintf(gpio_num, "%d", gpio_get(gpios));
    sprintf(pptr, "/sys/class/gpio/gpio%s", gpio_num);

    if (access(pptr, F_OK))
    {
        // 当文件不存在
        if (-1 == (fd = open("/sys/class/gpio/export", O_WRONLY)))
        {
            perror("open export error");
            exit(-1);
        }
        len = strlen(gpio_num);
        if (len != write(fd, gpio_num, len))
        {
            perror("write export error");
            close(fd);
            exit(-1);
        }
        close(fd);
    }
    if (-1 == gpio_write(pptr, "edge", "none"))
    {
        fprintf(stderr, "config edge error!");
        exit(-1);
    }
    if (-1 == gpio_write(pptr, "direction", "out"))
    {
        fprintf(stderr, "config direction error!");
        exit(-1);
    }
    while (1)
    {
        if (1 == atoi(argv[1]))
        {
            gpio_write(pptr, "value", "1");
            break;
        }
        if (2 == atoi(argv[1]))
        {
            gpio_write(pptr, "value", "0");
            break;
        }
    }

    return 0;
}

